package com.st.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

public class UploadUtil {

	public static String saveFile(HttpServletRequest request, String name, String path){
		
		FileOutputStream fos = null;
		
		try {
			Part part = request.getPart(name);
				
			// 字节输入流
			InputStream is = part.getInputStream();
			
			path = request.getServletContext().getRealPath(path);
			
			// 文件名的
			String fileName = UUID.randomUUID().toString();
			
			// 文件的后缀
			String suffix = part.getSubmittedFileName().substring(part.getSubmittedFileName().lastIndexOf("."));
			
			// 组合文件名
			fileName = fileName + suffix;
			
			// 写入到服务器的硬盘上
			fos = new FileOutputStream(path + "/" + fileName);
			
			byte[] buff = new byte[1024];
			while (true) {
				int length = is.read(buff);
				
				if (length < 0) {
					break;
				}
				
				fos.write(buff, 0, length);
			}
			
			fos.flush();
			
			return fileName;
		
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos!=null) fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}
}
